package com.wyh.domain.vo.gfive.treeVo.tree_util;

import com.wyh.domain.dto.gfive.LoginUser;
//import com.wyh.domain.vo.utils.MasterDataDepartmentTree;
//import com.wyh.domain.vo.utils.MasterDataTreeNode;
//import com.wyh.service.threemeterAbout.threemeterTree.*;
import com.wyh.domain.vo.gfive.treeVo.TreeNode;
import com.wyh.service.gfive.tree_service.*;
//import com.wyh.service.tree_service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class DepartmentTreeUtils {

    private final IOrganizationVOService iOrganizationVOService;
    private final IProjectVOService iProjectVOService;
    private final IBuildingUnitsVOService iBuildingUnitsVOService;
    private final ILayerVOService iLayerVOService;
    private final IRoomVOService iRoomVOService;
    private final RedisTemplate<String, Object> redisTemplate;

    @Autowired
    public DepartmentTreeUtils(
            IOrganizationVOService iOrganizationVOService,
            IProjectVOService iProjectVOService,
            IBuildingUnitsVOService iBuildingUnitsVOService,
            ILayerVOService iLayerVOService,
            IRoomVOService iRoomVOService,
            RedisTemplate<String, Object> redisTemplate
    ) {
        this.iOrganizationVOService = iOrganizationVOService;
        this.iProjectVOService = iProjectVOService;
        this.iBuildingUnitsVOService = iBuildingUnitsVOService;
        this.iLayerVOService = iLayerVOService;
        this.iRoomVOService = iRoomVOService;
        this.redisTemplate = redisTemplate;
    }

    // 更新部门树结构，并更新版本号
    public void updateDepartmentTree(Integer userId) {
        // 获取当前版本号
        String versionKey = "wyh:MasterDataDepartmentTree:globalVersion";
        Long currentVersion = (Long) redisTemplate.opsForValue().get(versionKey);

        // 增加版本号
        long newVersion = (currentVersion != null ? currentVersion + 1 : 1);

        // 构建新的树并存入 Redis
        buildDepartmentTree(userId, newVersion);

        // 更新 Redis 中的版本号
        redisTemplate.opsForValue().set(versionKey, newVersion);
    }

    // 从数据库中获取部门树结构的逻辑
    public List<TreeNode> fetchTreeFromDatabase() {
        UsernamePasswordAuthenticationToken authentication =
                (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Integer organizationid = loginUser.getUser().getOrganizationid();
        Integer userid = loginUser.getUser().getId();
        String account = loginUser.getUser().getAccount();
        return DepartmentTree.buildUserDepartmentTree(userid, organizationid,
                iOrganizationVOService.findAll(),
                iProjectVOService.findAllByConnected(account),
                iBuildingUnitsVOService.findAll(),
                iLayerVOService.findAll(),
                iRoomVOService.findAll());
    }

    // 从数据库中重建树并存入 Redis
    public DepartmentTreewithVersion buildDepartmentTree(Integer userId, long newVersion) {
        List<TreeNode> treeNodes = fetchTreeFromDatabase();
        DepartmentTreewithVersion departmentTreewithVersion = new DepartmentTreewithVersion();
        departmentTreewithVersion.setVersion(newVersion);
        departmentTreewithVersion.setTreeNodes(treeNodes);
        // 更新 Redis 中的树
        String redisKey = "wyh:MasterDataDepartmentTree:" + userId;
        redisTemplate.opsForValue().set(redisKey, departmentTreewithVersion);
        return departmentTreewithVersion;
    }

    // 获取部门树结构，检查版本号
    public DepartmentTreewithVersion getDepartmentTree(Integer userId) {
        long currentVersion = getCurrentVersionFromRedis();
        DepartmentTreewithVersion treeFromRedis = getTreeFromRedis(userId);
        if (treeFromRedis != null && treeFromRedis.getVersion() == currentVersion) {
            return treeFromRedis;
        } else {
            return buildDepartmentTree(userId, currentVersion);
        }
    }

    private DepartmentTreewithVersion getTreeFromRedis(Integer userId) {
        String redisKey = "wyh:MasterDataDepartmentTree:" + userId;
        return (DepartmentTreewithVersion) redisTemplate.opsForValue().get(redisKey);
    }

    private long getCurrentVersionFromRedis() {
        Long currentVersion = (Long) redisTemplate.opsForValue().get("wyh:MasterDataDepartmentTree:globalVersion");
        return (currentVersion != null) ? currentVersion : 0;
    }
}
